package kin.json;

import java.io.IOException;
import java.io.StringWriter;

import kin.test.Us;




import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerFactory;
import com.fasterxml.jackson.databind.ser.SerializerFactory;



public class JsonUtils {
	
    //private static final Log log = LogFactory.getLog(JsonUtils.class);

    private static final ObjectMapper mapper = new ObjectMapper();

    public static String jsonFromObject(Object object) {

        StringWriter writer = new StringWriter();
       // mapper.setPropertyNamingStrategy(new MyNameStrategy());
        SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier());
     //  mapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
       
		mapper.setSerializerFactory(serializerFactory);
        try {

            mapper.writeValue(writer, object);

        } catch (RuntimeException e) {

            throw e;

        } catch (Exception e) {

            //log.error("Unable to serialize to json: " + object, e);

            return null;

        }

        return writer.toString();

    }



    



    public static  Object objectFromJson(String json, Class cls) {

        Object object = null;
        
        mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY , true);
    	
		 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES ,false);
		
		 SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new MyBeanDeserializerModifier());
		 mapper.registerModule(module);
                    
            try {
				object = mapper.readValue(json, cls);
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
           
    	    // object=mapper.readValue(json, cls);
        /*catch (RuntimeException e) {

            log.error("Runtime exception during deserializing "

                    + klass.getSimpleName() + " from "

                    + StringUtils.abbreviate(json, 80));

            throw e;

        }*/ 

        /*    log.error("Exception during deserializing " + klass.getSimpleName()

                    + " from " + StringUtils.abbreviate(json, 80));*/
      
        

        return object;

    }

}
